package com.yu.boot.admin.web;

import com.lhy.commonweb.model.ResponseResult;
import com.lhy.commonweb.model.ResponseValidate;
import com.yu.boot.admin.model.User;
import com.yu.boot.admin.service.UserService;
import com.yu.boot.lib.util.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;

@Controller
@RequestMapping("login")
public class LoginController {

    @Autowired
    UserService userService;

    @Autowired
    HttpServletRequest request;

    @RequestMapping(value = "view")
    public String view() {
        return "login";
    }

    @RequestMapping(value = "login", method = {RequestMethod.POST, RequestMethod.GET})
    @ResponseBody
    public ResponseValidate login(User user) {
        User user1 = userService.getUserByName(user.getName());
        if (user1 == null) {
            return ResponseValidate.fail().setMsg("acount not exists");
        } else {
            if (!StringUtil.md5(user.getPass(), user.getName()).equalsIgnoreCase(user1.getPass())) {
                return ResponseValidate.fail().setMsg("密码输入不正确!");
            } else {
                request.getSession().setAttribute("user", user1);
                return ResponseValidate.ok();
            }
        }
    }

    @RequestMapping(value = "logout")
    public String logout() {
        request.getSession().invalidate();
        return "index";
    }

    @RequestMapping(value = "register/view")
    public String registerview() {
        return "register";
    }

    @RequestMapping(value = "exist", method = {RequestMethod.GET})
    @ResponseBody
    public ResponseValidate exist(User user) {
        boolean b = userService.existsBean(user);
        if (!b) {
            return ResponseValidate.ok();
        } else {
            return ResponseValidate.fail().setMsg("账号已存在!");
        }
    }

    @RequestMapping(value = "register", method = RequestMethod.POST)
    @ResponseBody
    public ResponseResult register(@RequestBody User user) {
        String pass = StringUtil.md5(user.getPass(), user.getName());
        user.setPass(pass).setCreated(new Date()).setStatus(true);
        userService.add(user);
        return ResponseResult.ok();
    }
}
